package com.webvihar.access2db.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.webvihar.access2db.R;
import com.webvihar.access2db.adapters.TablesAdapter;
import com.webvihar.access2db.asynctasks.A2DbAsyncWebRequestTask;
import com.webvihar.access2db.builders.RunShowQueryBuilder;
import com.webvihar.access2db.model.ShowQueryResult;
import com.webvihar.access2db.model.Table;
import com.webvihar.access2db.model.TableEntity;
import com.webvihar.access2db.restapi.A2DbRunShowQueryRequest;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.restapi.BaseA2DbQueryRequest;
import com.webvihar.access2db.restapi.IA2DbWebRequestDelegate;
import com.webvihar.access2db.utils.PreferencesManager;

public class TablesActivity extends BaseActivity implements OnItemClickListener, OnClickListener {

	private TextView titleTxt;
	private ListView tableList;
	private String databaseName;
	private ImageButton addTableBtn;
	private List<TableEntity> tableEntities;

	/** Called when the activity is first created. */
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		setContentView(R.layout.tables);
		loadDataFromIntent();
		updateDatabaseInPreferences();
		initUI();
		setTitleBar();
		registerContext();
		//		startTablesRequestProcess();
		executeQuery(getQueryBuilder().getShowTablesQuery(), new A2DbRunShowQueryRequest(), new RunShowQueryBuilder(), runQueryRequestHandler);
		setListeners();
	}

	private void registerContext() {
		registerForContextMenu(tableList);			
	}

	@Override
	protected void onResume() {
		super.onResume();
		executeQuery(getQueryBuilder().getShowTablesQuery(), new A2DbRunShowQueryRequest(), new RunShowQueryBuilder(), runQueryRequestHandler);
	}
	
	private void loadDataFromIntent() {
		databaseName = getValue(KEY_DATABASE_NAME, getIntent().getExtras());
	}

	private void updateDatabaseInPreferences() {
		PreferencesManager.setString(getApplicationContext(), PREF_SESSION_DBNAME, databaseName);
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		if(v.getId() == R.id.tables_lst) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			TableEntity tableEntity = tableEntities.get(info.position);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.context_menu, menu);
			menu.setHeaderTitle(tableEntity.tableName);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		TableEntity entity;
		Intent intent;
		switch (item.getItemId()) {
		case R.id.menu_edit_item:
			entity = tableEntities.get(info.position);
			intent = new Intent(TablesActivity.this, AddEditDeleteTableActivity.class);
			intent.putExtra(BaseActivity.KEY_TABLE_NAME, entity.tableName);
			intent.putExtra(BaseActivity.KEY_TABLE_MANAGEMENT_NAVIGATION_MODE, AddEditDeleteTableActivity.TABLE_MANAGEMENT_TYPE_EDIT);
			startActivity(intent);
			return(true);
		case R.id.menu_delete_item:
			entity = tableEntities.get(info.position);
			intent = new Intent(TablesActivity.this, AddEditDeleteTableActivity.class);
			intent.putExtra(BaseActivity.KEY_TABLE_NAME, entity.tableName);
			intent.putExtra(BaseActivity.KEY_TABLE_MANAGEMENT_NAVIGATION_MODE, AddEditDeleteTableActivity.TABLE_MANAGEMENT_TYPE_DELETE);
			startActivity(intent);
			return(true);
		default:
			return(super.onOptionsItemSelected(item));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.database_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.menu_database_refresh:	
			// startTablesRequestProcess();
			executeQuery(getQueryBuilder().getShowTablesQuery(), new A2DbRunShowQueryRequest(), new RunShowQueryBuilder(), runQueryRequestHandler);
			break;
		case R.id.menu_database_query_editor:
			navigateToQueryEditor();
			break;
		default:
			break;
		}
		return true;
	}

	private void navigateToQueryEditor() {
		Intent intent = new Intent(TablesActivity.this, QueryEditorActivity.class);
		startActivity(intent);
	}

	private void setListeners() {
		tableList.setOnItemClickListener(this);
		addTableBtn.setOnClickListener(this);
	}

	private void executeQuery(String query, BaseA2DbQueryRequest request, IA2DbWebRequestDelegate deligate, Handler handler) {
		request.encoded = true;
		request.host = 	PreferencesManager.getString(getApplicationContext(), PREF_SESSION_HOST);
		request.port =  PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PORT);
		request.username = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_USERNAME);
		request.password = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PASSWORD);
		request.dbname = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_DBNAME);
		request.query = query;
		request.requestDelegate = deligate;
		new A2DbAsyncWebRequestTask(true, getApplicationContext(), handler, getProgressDialog()).execute(request);
	}

	private Handler runQueryRequestHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			A2DbWebResult<ShowQueryResult> response = (A2DbWebResult<ShowQueryResult>) msg.obj;
			if(response == null) {
				showToast("Response is null");
				TablesActivity.this.finish();
			} else if(response.entity == null) {
				showToast("Server not found...");
				TablesActivity.this.finish();
			} else if(response.entity.result == null){
				showToast(response.entity.error+"");
				TablesActivity.this.finish();
			} else {
				setAdapter(response.entity.result);            	
			}
		}
	};

	@SuppressWarnings("unused")
	private Handler runDeleteQueryRequestHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			A2DbWebResult<ShowQueryResult> response = (A2DbWebResult<ShowQueryResult>) msg.obj;
			if(response == null) {
				showToast("Response is null");
				TablesActivity.this.finish();
			} else if(response.entity == null) {
				showToast("Server not found...");
				TablesActivity.this.finish();
			} else if(response.entity.result == null){
				showToast(response.entity.error+"");
				TablesActivity.this.finish();
			} else {
				setAdapter(response.entity.result);            	
			}
		}
	};


	public void setTitleBar() {
		titleTxt = (TextView) findViewById(R.id.title_txt);
		titleTxt.setText(getString(R.string.tables_txt));
		addTableBtn = (ImageButton) findViewById(R.id.title_action_image_btn);
		addTableBtn.setVisibility(View.VISIBLE);
	}

	private void initUI() {
		tableList = (ListView)findViewById(R.id.tables_lst);
	}

	private void setAdapter(Table table) {
		tableList.setAdapter(new TablesAdapter(this, getTableList(table)));
	}

	private List<TableEntity> getTableList(Table table) {
		tableEntities = new ArrayList<TableEntity>();
		String[][] data = table.data;
		for(int i=0; i<data.length; i++) {
			tableEntities.add(new TableEntity(data[i][0]));
		}
		return tableEntities;
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
		TableEntity tableEntity = (TableEntity)adapter.getItemAtPosition(position);
		PreferencesManager.setString(this, PREF_SESSION_TABLE_NAME, tableEntity.tableName);
		Intent intent = new Intent(TablesActivity.this, TableDataActivity.class); 
		intent.putExtra(KEY_TABLE_NAME, tableEntity.tableName);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		if(v == addTableBtn) {
			Intent intent = new Intent(TablesActivity.this, AddEditDeleteTableActivity.class);
			intent.putExtra(BaseActivity.KEY_TABLE_NAME, "");
			intent.putExtra(KEY_TABLE_MANAGEMENT_NAVIGATION_MODE, AddEditDeleteTableActivity.TABLE_MANAGEMENT_TYPE_ADD);
			startActivity(intent);
		}
	}
}